<template>
  <div class="add-product">
    <h1 class="back-title" @click="$router.go(-1)"><i class="iconfont icon-fanhui"></i>{{form.id!=0?'编辑':'新增'}}产品</h1>
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" :label-position="labelPosition">
      <h2 class="litter-title">产品基本信息</h2>
      <el-form-item label="英文名称：" prop="productEname" class="rule">
        <el-input type="text" v-model="form.productEname" size="medium" maxlength="120" show-word-limit></el-input>
      </el-form-item>
      <el-form-item label="中文名称：" prop="productName">
        <el-input type="text" v-model="form.productName" size="medium" maxlength="100" show-word-limit></el-input>
      </el-form-item>
      <div class="line">
        <el-form-item label="产品类型：" prop="productType">
          <el-select v-model="form.productType" size="medium">
            <el-option v-for="item,index in treeProductUnit" :key="index"
                       :label="item.dictValue" :value="item.dictKey"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品规格：" prop="productSpecification">
          <el-input type="text" v-model="form.productSpecification" size="medium"></el-input>
        </el-form-item>
        <el-form-item label="产品型号：" prop="productModel">
          <el-input type="text" v-model="form.productModel" size="medium"></el-input>
        </el-form-item>
      </div>
      <div class="line">
        <el-form-item label="产品分组：" prop="typeId" class="rule">
          <el-cascader size="medium"
                       v-model="typeIdWeb"
                       class="input"
                       change-on-select
                       :options="treeOptions"
                       :props="{ expandTrigger: 'hover',label: 'text', value: 'id'}"
                       @change="handleChange"></el-cascader>
        </el-form-item>
        <el-form-item label="计量单位：" prop="productUnit" class="rule">
          <el-select v-model="form.productUnit" size="medium">
            <el-option v-for="item,index in treePackUnit" :key="index"
                       :label="item.dictValue" :value="item.dictKey"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="产品编码：" prop="productCode" class="rule">
          <el-input type="text" v-model="form.productCode" size="medium"></el-input>
        </el-form-item>
      </div>
      <div class="line">
        <el-form-item label="最小起订量：" prop="minimum">
          <el-input type="number" v-model="form.minimum" size="medium"></el-input>
        </el-form-item>
        <el-form-item label="海关编码：" prop="hsCode">
          <el-input type="text" v-model="form.hsCode" size="medium"></el-input>
        </el-form-item>
        <el-form-item label="产品来源：" prop="productSource">
          <el-select v-model="form.productSource" size="medium">
            <el-option v-for="item,index in treeSource" :key="index"
                       :label="item.dictValue" :value="item.dictKey"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="产品关键词：" prop="productKeyWord">
        <ul class="key-word">
          <li v-for="item,index in keyWords" :key="index">
            <el-input type="text" v-model="item.title" size="medium" maxlength="128" show-word-limit
                      placeholder="请按正确格式填写：“修饰词+产品中心词+应用场景”，例如：“Red 8GB mp3 for sports”"></el-input>
            <img src="../../../public/img/email/icon/icon-del.png" alt="" v-show="index>0"
                 @click="keyWords.splice(index,1)">
          </li>
        </ul>
        <el-button size="mini" @click="keyWords.push({title:''})" v-show="keyWords.length<5">+添加更多关键词</el-button>
      </el-form-item>
      <h2 class="litter-title">价格信息</h2>
      <div class="line">
        <el-form-item class="spec" label="离岸价：" prop="productSpec.offshorePrice">
          <el-input type="number" v-model="form.productSpec.offshorePrice" size="medium"></el-input>
        </el-form-item>
        <el-form-item class="spec" label="价格币种：" prop="productSpec.offshoreCurrencyUnit">
          <el-select v-model="form.productSpec.offshoreCurrencyUnit" size="medium">
            <el-option v-for="item,index in treeMoneyUnit" :key="index"
                       :label="item.dictValue" :value="item.dictKey"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="line">
        <el-form-item class="spec" label="含税成本：" prop="productSpec.costPrice">
          <el-input type="number" v-model="form.productSpec.costPrice" size="medium"></el-input>
        </el-form-item>
        <el-form-item class="spec" label="价格币种：" prop="productSpec.costCurrencyUnit">
          <el-select v-model="form.productSpec.costCurrencyUnit" size="medium">
            <el-option v-for="item,index in treeMoneyUnit" :key="index"
                       :label="item.dictValue" :value="item.dictKey"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="line">
        <el-form-item class="spec" label="单价：" prop="productSpec.unitPrice">
          <el-input type="number" v-model="form.productSpec.unitPrice" size="medium"></el-input>
        </el-form-item>
        <el-form-item class="spec" label="价格币种：" prop="productSpec.unitPriceCurrency">
          <el-select v-model="form.productSpec.unitPriceCurrency" size="medium">
            <el-option v-for="item,index in treeMoneyUnit" :key="index"
                       :label="item.dictValue" :value="item.dictKey"></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="line">
        <el-form-item label="1档价格：" prop="productSpec.firstPrice">
          <el-input type="number" v-model="form.productSpec.firstPrice" size="medium"></el-input>
        </el-form-item>
        <el-form-item label="1档数量：" prop="productSpec.firstNumber">
          <el-input type="number" v-model="form.productSpec.firstNumber" size="medium"></el-input>
        </el-form-item>
      </div>
      <div class="line">
        <el-form-item label="2档价格：" prop="productSpec.secondPrice">
          <el-input type="number" v-model="form.productSpec.secondPrice" size="medium"></el-input>
        </el-form-item>
        <el-form-item label="2档数量：" prop="productSpec.secondNumber">
          <el-input type="number" v-model="form.productSpec.secondNumber" size="medium"></el-input>
        </el-form-item>
      </div>
      <div class="line">
        <el-form-item label="样品价格：" prop="productSpec.samplePrice">
          <el-input type="number" v-model="form.productSpec.samplePrice" size="medium"></el-input>
        </el-form-item>
        <el-form-item label="样品数量：" prop="productSpec.sampleNumber">
          <el-input type="number" v-model="form.productSpec.sampleNumber" size="medium"></el-input>
        </el-form-item>
      </div>
      <h2 class="litter-title">包装信息</h2>
      <div class="line">
        <el-form-item label="包装单位：" prop="productSpec.packingUnit">
          <el-select v-model="form.productSpec.packingUnit" size="medium">
            <el-option v-for="item,index in treePackUnit" :key="index"
                       :label="item.dictValue" :value="item.dictKey"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="每包装数量：" prop="productSpec.packageNumber">
          <el-input type="number" v-model="form.productSpec.packageNumber" size="medium"></el-input>
        </el-form-item>
      </div>
      <div class="line">
        <el-form-item class="hasUnit" label="包装体积：" prop="productSpec.packageVolume">
          <el-input type="number" v-model="form.productSpec.packageVolume" size="medium"></el-input>
          <span>m³</span>
        </el-form-item>
        <el-form-item class="hasUnit" label="包装毛重：" prop="productSpec.packagingGrossWeight">
          <el-input type="number" v-model="form.productSpec.packagingGrossWeight" size="medium"></el-input>
          <span>KG</span>
        </el-form-item>
      </div>
      <div class="line">
        <el-form-item class="hasUnit" label="外箱长：" prop="productSpec.outerBoxLong">
          <el-input type="number" v-model="form.productSpec.outerBoxLong" size="medium"></el-input>
          <span>CM</span>
        </el-form-item>
        <el-form-item class="hasUnit" label="外箱宽：" prop="productSpec.outerBoxWidth">
          <el-input type="number" v-model="form.productSpec.outerBoxWidth" size="medium"></el-input>
          <span>CM</span>
        </el-form-item>
      </div>
      <div class="line">
        <el-form-item label="外箱高：" prop="productSpec.outerBoxHigh">
          <el-input type="number" v-model="form.productSpec.outerBoxHigh" size="medium"></el-input>
          <span>CM</span>
        </el-form-item>
        <el-form-item label="产品净重" prop="productSpec.productWeight">
          <el-input type="number" v-model="form.productSpec.productWeight" size="medium"></el-input>
          <span>KG</span>
        </el-form-item>
      </div>
      <el-form-item label="包装说明：">
        <el-input type="textarea" v-model="form.productSpec.packageInstruction" style="width: 800px"
                  :show-word-limit="true" maxlength="200"
                  :rows="4"
                  size="medium"></el-input>
      </el-form-item>
      <h2 class="litter-title">产品详情</h2>
      <el-form-item label="产品主图：" prop="productImageList" class="product-image">
        <div class="btn" v-show="form.productImageList.length<5">
          <el-button type="primary" size="mini" @click="upload('productImageList')">本地上传</el-button>
          <el-button type="primary" size="mini" @click="cloundUpload(1)">云盘上传</el-button>
        </div>
        <ul class="image" @mouseleave="frag=-1">
          <li v-for="item,index in form.productImageList" :key="index" @mouseover="frag=index">
            <img :src="item.fileUrl" alt="" class="pro-img">
            <div class="extra" :style="{display:frag==index?'block':'none'}">
              <img src="../../../public/img/email/icon/icon-del-white.png" alt=""
                   @click="form.productImageList.splice(index,1)">
            </div>
          </li>
        </ul>
        <p>建议尺寸：700*700像素，图片大小在3M以内,图片支持.jpg  .jpeg .png 格式</p>
      </el-form-item>
      <el-form-item label="产品视频：">
        <div class="btn" v-show="form.productAttachList.length==0">
          <el-button type="primary" size="mini" @click="upload('productAttachList')">本地上传</el-button>
          <el-button type="primary" size="mini" @click="cloundUpload(0)">云盘上传</el-button>
        </div>
        <ul v-show="form.productAttachList.length>0" class="video">
          <li v-for="item,index in form.productAttachList" :key="index">
            <video controls class="product_video" width="213px" height="150px" :poster="item.previewUrl">
              <source :src="item.fileUrl" type="video/mp4">
            </video>
            <img src="../../../public/img/email/icon/icon-remove.png" alt="" title="删除产品视频"
                 @click="form.productAttachList.splice(index,1)">
          </li>
        </ul>
        <p>建议视频比例为1:1或16:9，视频大小在15M以内，视频支持.mp4  .webm  .ogg格式</p>
      </el-form-item>
      <el-form-item label="产品详情：" class="editor" style="max-width: 1200px">
        <SimpleUE :config="{initialFrameHeight: 600}"
                  ref="childEditor" :catchData="getContent"
                  @ready="ready"></SimpleUE>
      </el-form-item>
      <el-form-item label="上架时间：" v-show="!$route.query.type">
        <el-radio-group v-model="form.releaseStatus">
          <el-radio :label="1">立即上架(上架后同步到官网）</el-radio>
          <el-radio :label="0">放置仓库中</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item class="common-btn">
        <el-button @click="$router.go(-1)" size="small">取 消</el-button>
        <el-button type="primary" @click="submitForm('ruleForm')" :loading="loading" size="small" style="width: 122px">
          发布产品信息
        </el-button>
      </el-form-item>
    </el-form>
    <input type="file" @change="(val)=>{onChange(val,'productImageList')}" accept="image/jpg,image/png,image/jpeg"
           ref="productImageList" hidden>
    <input type="file" @change="(val)=>{onChange(val,'productAttachList')}" accept='video/mp4,video/webm,audio/ogg'
           ref="productAttachList" hidden>
    <!--云盘选择-->
    <CloundUp ref="cloundUp" @setFile="setFile"></CloundUp>
  </div>
</template>

<script>
    import SimpleUE from '@/components/ueditor/simpleUE'
    import CloundUp from '@/components/product/DialogColund'
    import {addProduct, getleftMenu, getProductDetails, modifyProduct, getProCode} from '@/api/product'
    import {getDictory, getRollbackID} from '@/util/util'
    import {uploadOss} from '@/util/file'
    import {mapGetters} from 'vuex'

    export default {
        name: 'addProduct',
        components: {SimpleUE, CloundUp},
        data() {
            return {
                loading: false,
                labelPosition: 'left',
                form: {
                    id: '',
                    productEname: '',//英文名称
                    productName: '',//中文名称
                    productSpecification: '',//规格名称
                    productType: '',//产品类型
                    productSource: '',//产品来源
                    productModel: '',//产品型号
                    productCode: '',//产品编码
                    typeId: '',//产品分组 - n
                    productUnit: '',//计量单位
                    minimum: '',//最小起订量
                    hsCode: '',//海关编码
                    productKeyWord: '',//关键词  , 分割
                    productSpec: {//规格对象
                        offshorePrice: '',//离岸价
                        offshoreCurrencyUnit: '',//离岸价币种
                        costPrice: '',//含税成本价
                        costCurrencyUnit: '',//含税成本价单位
                        unitPrice: '',//单价
                        unitPriceCurrency: '',//单价币种
                        firstPrice: '',//一档价格
                        firstNumber: '',//一档数量
                        secondPrice: '',//二档价格
                        secondNumber: '',//二档数量
                        samplePrice: '',//样品价格
                        sampleNumber: '',//样品数量
                        packingUnit: '',//包装单位
                        packageNumber: '',//每包装产品数
                        packageVolume: '',//包装体积
                        packageInstruction: '',//包装说明
                        packagingGrossWeight: '',//包装毛重
                        outerBoxLong: '',//外箱长
                        outerBoxWidth: '',//外箱宽
                        outerBoxHigh: '',//外箱高
                        productWeight: '',//产品净重
                    },
                    productImageList: [],//产品图片列表
                    productAttachList: [],//产品视频列表
                    remarks: '',//富文本描述
                    releaseStatus: 0,//是否上架
                },
                treeOptions: [],//产品分组
                treeSource: [],//产品来源
                treeProductUnit: [],//产品类型
                treePackUnit: [],//计量单位
                treeMoneyUnit: [],//币种单位
                typeIdWeb: [],//产品分组current
                keyWords: [{title: ''}],//产品关键词
                frag: -1,
                accept: '',
                rules: {
                    productEname: [
                        {required: true, message: '请输入产品英文名称', trigger: 'blur'},
                        {min: 1, max: 120, message: '最多可输120个字符', trigger: 'blur'}
                    ],
                    typeId: [
                        {required: true, message: '请选择产品分组', trigger: 'change'},
                    ],
                    productCode: [
                        {required: true, message: '请输入产品编码', trigger: 'blur'},
                    ],
                    productUnit: [
                        {required: true, message: '请选择计量单位', trigger: 'change'},
                    ],
                    'productSpec.offshorePrice': [
                        {required: true, message: '请输入离岸价', trigger: 'blur'},
                    ],
                    'productSpec.offshoreCurrencyUnit': [
                        {required: true, message: '请选择离岸价币种', trigger: 'change'},
                    ],
                    'productSpec.costPrice': [
                        {required: true, message: '请输入含税成本价', trigger: 'blur'},
                    ],
                    'productSpec.costCurrencyUnit': [
                        {required: true, message: '请选择含税成本价币种', trigger: 'change'},
                    ],
                    'productSpec.unitPrice': [
                        {required: true, message: '请输入产品单价', trigger: 'blur'},
                    ],
                    'productSpec.unitPriceCurrency': [
                        {required: true, message: '请选择产品单价币种', trigger: 'change'},
                    ],
                    productImageList: [
                        {type: 'array', required: true, message: '至少上传一张产品图片', trigger: 'change'},
                    ]
                },
                imageAccept: ['image/jpg', 'image/png', 'image/jpeg']
            }
        },
        computed: {
            ...mapGetters(["permission"]),
        },
        mounted() {
            //判断新增还是编辑
            this.form.id = this.$route.path == '/product/add' ? '' : this.$route.params.id;
            this.treeSource = getDictory('product_source').children;
            this.treePackUnit = getDictory('package_unit').children;
            this.treeMoneyUnit = getDictory('currency').children;
            this.treeProductUnit = getDictory('product_type').children;
        },
        methods: {
            //开始初始化 - 富文本
            ready() {
                if (this.form.id != 0) {
                    this.getDetail()
                } else {
                    //获取产品分组
                    this.getProCode();
                    this.getTree();
                }
            },
            getDetail() {
                getProductDetails(this.form.id).then((res) => {
                    this.keyWords = [];
                    if (res.data.success) {
                        this.form = res.data.data;
                        //转换参数 - 关键词 - 产品分组 - 富文本
                        this.$refs.childEditor.insertEditor(this.form.remarks);
                        const arr = this.form.productKeyWord.split(",");
                        for (let item of arr) {
                            this.keyWords.push({title: item})
                        }
                        this.typeIdWeb = [this.form.typeId];
                        this.getTree();
                    }
                })
            },
            //提交产品信息
            submitForm(name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        //处理参数 - 产品关键词，富文本信息
                        let arr = [];
                        for (let item of this.keyWords) {
                            arr.push(item.title)
                        }
                        this.form.productKeyWord = arr.join(',');//form.releaseStatus
                        this.$confirm(` <div style="margin: 10px;">
 <p style="line-height: 30px;font-size: 14px;">立即${this.form.releaseStatus==1?'上架产品至官网!':'保存产品至仓库中!'}</p>
 </div>`, '保存产品', {
                            dangerouslyUseHTMLString: true,
                            closeOnClickModal: false,
                            closeOnPressEscape: false,
                            confirmButtonText: '确定',
                            cancelButtonText: '取 消',
                        }).then(() => {
                            this.loading = true;
                            this.form.remarks = encodeURIComponent(this.form.remarks);
                            if (this.form.id != 0) {
                                modifyProduct(this.form).then((res) => { // 新增
                                    this.dealEnd(res);
                                }).catch(() => {
                                    this.loading = false;
                                    this.form.remarks = decodeURIComponent(this.form.remarks);
                                })
                            } else {
                                addProduct(this.form).then((res) => { // 新增
                                    this.dealEnd(res);
                                }).catch(() => {
                                    this.loading = false;
                                    this.form.remarks = decodeURIComponent(this.form.remarks);
                                })
                            }
                        }).catch(() => {

                        })
                    } else {
                        return false;
                    }
                });
            },
            //初始化云盘
            cloundUpload(type) {
                let maxNum = 1, targetAccept = '';
                if (type) {//图片
                    maxNum = 5 - this.form.productImageList.length;
                    targetAccept = 'jpg,png,jpeg'
                } else {
                    maxNum = 1;
                    targetAccept = 'mp4,webm,ogg'
                }
                this.$refs.cloundUp.init({
                    maxNum: maxNum,
                    accept: targetAccept
                });
            },
            //云盘选择结果
            setFile(type, fileList) {
                let name = type ? 'productImageList' : 'productAttachList';
                this.form[name] = this.form[name].concat(fileList)
            },
            upload(name) {
                this.$refs[name].dispatchEvent(new MouseEvent('click'))
            },
            onChange(event, name) {
                const file = event.target.files[0];
                //判断图片： 3M   视频：15M
                let maxSize1 = 0;
                let msg = '';
                if (this.imageAccept.includes(file.type)) {//图片
                    maxSize1 = 3145728;
                    msg = '图片太大，无法上传！产品图片最大支持3M';
                } else {//图片
                    maxSize1 = 15728640;
                    msg = '视频太大，无法上传！产品视频最大支持15M';
                }
                if (file.size > maxSize1) {
                    this.$message({
                        message: msg,
                        type: 'success'
                    });
                    this.$refs[name].value = '';
                    return false
                }
                uploadOss(file, 0).then(result => {
                    const params = {
                        fileUrl: result.url,
                        fileSize: file.size,
                        fileName: result.oldName
                    }
                    this.form[name].push(params);
                    this.$refs[name].value = '';
                    this.$refs.ruleForm.validate()
                }).catch(err => {
                    this.$refs[name].value = '';
                    this.$message({
                        type: 'success',
                        message: '文件上传失败,请重新上传!'
                    })
                })
            },
            getContent(val) {
                this.form.remarks = val;
            },
            handleChange(file, fileList) {
                this.form.typeId = file[file.length - 1];
            },
            //获取产品编码
            getProCode() {
                getProCode().then((res) => { // 获取树性结构
                    if (res.data.success) {
                        this.form.productCode = res.data.data;
                    }
                })
            },
            getTree() {
                getleftMenu().then((res) => { // 获取树性结构
                    if (res.data.success) {
                        const result = res.data.data;
                        if (this.permission.product_company_add) {
                            this.treeOptions = result;
                        } else {
                            for (let item of result) {
                                if (item.text == '自建目录') {
                                    this.treeOptions = [item];
                                }
                            }
                        }
                        this.typeIdWeb = getRollbackID(this.treeOptions, this.form.typeId)
                        let end = []
                        this.typeIdWeb.map(item => {
                            end.push(item.toString())
                        })
                        this.typeIdWeb = end;
                    }
                })
            },
            dealEnd(res) {
                this.loading = false
                if (res.data.success) {
                    this.$message({
                        message: res.data.msg,
                        type: 'success'
                    })
                    this.$router.go(-1)
                } else {
                    this.$message({
                        message: res.data.msg,
                        type: 'success'
                    })
                }
            }
        }
    }
</script>
<style lang="scss" scoped>
  @import "../../styles/product";
</style>
